#ifdef _WIN32
    #include <conio.h>  // Windows系统使用conio.h
#else
    #include <termios.h>
    #include <unistd.h>
    #include <fcntl.h>
#endif
#include <iostream>
#include "Car.h"
#include <vector>
#include <fstream>

using namespace std;

// 跨平台清空终端的函数
void clearTerminal() {
    // 判断操作系统类型
#ifdef _WIN32
    // Windows系统使用cls命令
    system("cls");
#else
    // Linux、macOS等类Unix系统使用clear命令
    system("clear");
#endif
}

// 带确认的清空函数
void clearTerminalWithPrompt() {
    std::cout << "按y进入系统界面";
    char response;
    std::cin >> response;
    
    if (response == 'y' || response == 'Y') {
        clearTerminal();
    } else {
        std::cout << "系统退出" << std::endl;
        exit(0);
    }
}

// Linux下模拟_getch()函数
#ifdef __linux__
int _getch() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

int _kbhit() {
    struct termios oldt, newt;
    int ch;
    int oldf;

    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
    fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

    ch = getchar();

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    fcntl(STDIN_FILENO, F_SETFL, oldf);

    if (ch != EOF) {
        ungetc(ch, stdin);
        return 1;
    }

    return 0;
}
#endif

int main() {
    vector<Car> cars;
    vector<Student> students;

    Car car1("cqusn00010001");
    Car car2("cqusn00020002");
    Car car3("cqusn00030003");
    Car car4("cqusn00040004");
    Car car5("cqusn00050005");
    Car car6("cqusn00060006");
    Car car7("cqusn00070007");
    Car car8("cqusn00080008");
    Car car9("cqusn00090009");
    Car car10("cqusn00100010");

    Student student1 = {"20210001", "张三"};
    Student student2 = {"20210002", "李四"};   
    Student student3 = {"20210003", "王五"};
    Student student4 = {"20210004", "赵六"};       
    Student student5 = {"20210005", "钱七"};
    Student student6 = {"20210006", "孙八"};
    Student student7 = {"20210007", "周九"};
    Student student8 = {"20210008", "吴十"};
    Student student9 = {"20210009", "郑十一"};
    Student student10 = {"20210010", "冯十二"};

    car1.assignStudent(student1);
    car2.assignStudent(student2);
    car3.assignStudent(student3);
    car4.assignStudent(student4);
    car5.assignStudent(student5);
    car6.assignStudent(student6);
    car7.assignStudent(student7);
    car8.assignStudent(student8);
    car9.assignStudent(student9);
    car10.assignStudent(student10);

    cars.push_back(car1);
    cars.push_back(car2);
    cars.push_back(car3);   
    cars.push_back(car4);
    cars.push_back(car5);
    cars.push_back(car6);
    cars.push_back(car7);
    cars.push_back(car8);
    cars.push_back(car9);
    cars.push_back(car10);
    //调用car1配件的save函数
    car1.getChassis().save();
    car1.getChassis().getTires(0).save();
    car1.getChassis().getTires(1).save();
    car1.getChassis().getTires(2).save();   
    car1.getChassis().getTires(3).save();
    car1.getAGXKit().save();
    car1.getStereoCamera().save();
    car1.getLiDAR().save();
    car1.getGyroscope().save();
    car1.getLCDScreen().save();
    car1.getBettery().save();
    

    int totalCars = cars.size();

    string filename = "cars_data.bin";
    if (Car::saveCarsToFile(cars, filename)) {
        cout << "小车信息保存成功！文件：" << filename << endl;
    } else {
        cerr << "小车信息保存失败！" << endl;
        return 1;
    }

    vector<Car> loadedCars;
    if (Car::loadCarsFromFile(loadedCars, filename)) {
        cout << "成功加载 " << loadedCars.size() << " 台小车信息" << endl;
    } else {
        cerr << "小车信息加载失败！" << endl;
        return 1;
    }

    int currentIndex = 0;

    clearTerminalWithPrompt();
    cout << "===============================================" << endl;
    cout << "          小车信息管理系统 - 操作界面" << endl;
    cout << "===============================================" << endl;
    cout << "操作说明：" << endl;
    cout << "  p / P → 查看下一台小车信息" << endl;
    cout << "  n / N → 查看上一台小车信息" << endl;
    cout << "  x / X → 退出系统" << endl;
    cout << "===============================================" << endl;
    cout << "\n提示：当前无选中小车，请按 'p' 查看第一台小车！" << endl;

    while (true) {
        if (_kbhit()) {
            char key = _getch();

            if (key == 'x' || key == 'X') {
                clearTerminal();
                cout << "===============================================" << endl;
                cout << "          小车信息管理系统 - 退出" << endl;
                cout << "===============================================" << endl;
                cout << "系统已安全退出，感谢使用！" << endl;
                break;
            }
            else if (key == 'p' || key == 'P') {
                if (currentIndex >= totalCars - 1) {
                    clearTerminal();
                    cout << "===============================================" << endl;
                    cout << "          小车信息管理系统 - 提示" << endl;
                    cout << "===============================================" << endl;
                    cout << "  已到达最后一台小车（共" << totalCars << "台），无法继续下翻！" << endl;
                    if (currentIndex != -1) {
                        cout << "\n【当前小车 - 第" << currentIndex + 1 << "台】" << endl;
                        loadedCars[currentIndex].displayCarInfo();
                    }
                }
                else {
                    currentIndex++;
                    clearTerminal();
                    cout << "===============================================" << endl;
                    cout << "          小车信息管理系统 - 当前小车" << endl;
                    cout << "===============================================" << endl;
                    cout << "当前：第" << currentIndex + 1 << "台 / 共" << totalCars << "台" << endl;
                    cout << "操作提示：按'n'上一台 | 'p'下一台 | 'x'退出" << endl;
                    cout << "===============================================" << endl;
                    loadedCars[currentIndex].displayCarInfo();
                }
            }
            else if (key == 'n' || key == 'N') {
                if (currentIndex <= 0) {
                    clearTerminal();
                    cout << "===============================================" << endl;
                    cout << "          小车信息管理系统 - 提示" << endl;
                    cout << "===============================================" << endl;
                    cout << "  已到达第一台小车，无法继续上翻！" << endl;
                    if (currentIndex != -1) {
                        cout << "\n【当前小车 - 第" << currentIndex + 1 << "台】" << endl;
                        loadedCars[currentIndex].displayCarInfo();
                    }
                }
                else {
                    currentIndex--;
                    clearTerminal();
                    cout << "===============================================" << endl;
                    cout << "          小车信息管理系统 - 当前小车" << endl;
                    cout << "===============================================" << endl;
                    cout << "当前：第" << currentIndex + 1 << "台 / 共" << totalCars << "台" << endl;
                    cout << "操作提示：按'n'上一台 | 'p'下一台 | 'x'退出" << endl;
                    cout << "===============================================" << endl;
                    loadedCars[currentIndex].displayCarInfo();
                }
            }
            else {
                clearTerminal();
                cout << "===============================================" << endl;
                cout << "          小车信息管理系统 - 错误提示" << endl;
                cout << "===============================================" << endl;
                cout << " 无效操作！请按以下说明按键：" << endl;
                cout << "  p/P → 下一台 | n/N → 上一台 | x/X → 退出" << endl;
                if (currentIndex != -1) {
                    cout << "\n【当前小车 - 第" << currentIndex + 1 << "台】" << endl;
                    loadedCars[currentIndex].displayCarInfo();
                }
            }
        }
    }
    
    system("pause");
    return 0;
}
